package com.luo.backend.service;

import com.luo.backend.dto.MerchantStatisticsResponse;
import com.luo.backend.entity.Order;
import com.luo.backend.repository.FoodRepository;
import com.luo.backend.repository.OrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家统计服务
 */
@Service
public class MerchantStatisticsService {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantStatisticsService.class);
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    /**
     * 获取统计概览
     */
    public MerchantStatisticsResponse getStatisticsOverview(Long merchantId, LocalDate date) {
        logger.info("获取商家统计概览 - merchantId: {}, date: {}", merchantId, date);
        
        if (date == null) {
            date = LocalDate.now();
        }
        
        LocalDateTime startOfDay = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(date, LocalTime.MAX);
        
        // 今日订单
        List<Order> todayOrders = orderRepository.findByMerchantIdAndCreatedAtBetween(
            merchantId, startOfDay, endOfDay);
        
        Long todayOrdersCount = (long) todayOrders.size();
        
        // 今日营收（已支付的订单）
        BigDecimal todayRevenue = todayOrders.stream()
            .filter(order -> !"pending".equals(order.getStatus()) && !"cancelled".equals(order.getStatus()))
            .map(Order::getTotalAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 待处理订单数（pending状态）
        Long pendingOrders = orderRepository.countByMerchantIdAndStatus(merchantId, "pending");
        
        // 今日下单客户数（去重）
        Long todayCustomers = todayOrders.stream()
            .map(Order::getUserId)
            .distinct()
            .count();
        
        // 商品总数
        Long totalFoods = foodRepository.countByMerchantId(merchantId);
        
        // 在售商品数（status=1）
        Long onlineFoods = foodRepository.countByMerchantIdAndStatus(merchantId, 1);
        
        logger.info("统计结果 - 今日订单: {}, 今日营收: {}, 待处理: {}, 今日客户: {}, 商品总数: {}, 在售: {}",
            todayOrdersCount, todayRevenue, pendingOrders, todayCustomers, totalFoods, onlineFoods);
        
        return new MerchantStatisticsResponse(
            todayOrdersCount,
            todayRevenue,
            pendingOrders,
            todayCustomers,
            totalFoods,
            onlineFoods
        );
    }
}





